import argparse
import json
import os
from dataclasses import dataclass
from typing import List

import jinja2


@dataclass
class EventTypeProperty:
    name: str
    datatype: str
    definition: str


@dataclass
class EventType:
    name: str
    kind: str
    definition: str
    min_agent_version: str
    properties: List[EventTypeProperty]


def build_event_types(json_top_node):
    event_types = []
    for et in json_top_node["secl"]:
        event_type = EventType(et["name"], et["type"], et["definition"], et["from_agent_version"], [])
        for p in et["properties"]:
            prop = EventTypeProperty(p["name"], p["type"], p["definition"])
            event_type.properties.append(prop)
        event_types.append(event_type)
    return event_types


def fill_template(event_types, template_name):
    env = jinja2.Environment(
        loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), "templates")),
        autoescape=jinja2.select_autoescape(),
        trim_blocks=True,
    )
    templ = env.get_template(template_name)
    return templ.render(event_types=event_types)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Generate SECL documentation")
    parser.add_argument("--input", type=str, help="input json file generated by the accessors generator")
    parser.add_argument("--output", type=str, help="output file")
    parser.add_argument("--template", type=str, default="agent_expressions.md", help="template used for the generation")
    args = parser.parse_args()

    secl_json_file = open(args.input)
    json_top_node = json.load(secl_json_file)
    secl_json_file.close()

    event_types = build_event_types(json_top_node)

    output_file = open(args.output, "w")
    print(fill_template(event_types, args.template), file=output_file)
    output_file.close()
